package com.wingsoft.common.core.page;

import com.alibaba.fastjson2.JSONObject;
import com.wingsoft.common.core.text.Convert;
import com.wingsoft.common.utils.ServletUtils;
import org.apache.commons.lang3.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * 表格数据处理
 *
 * @author fyadmin
 */
public class TableSupport {
    /**
     * 当前记录起始索引
     */
    public static final String PAGE_NUM = "pageNum";

    /**
     * 每页显示记录数
     */
    public static final String PAGE_SIZE = "pageSize";

    /**
     * 排序列
     */
    public static final String ORDER_BY_COLUMN = "orderByColumn";

    /**
     * 排序的方向 "desc" 或者 "asc".
     */
    public static final String IS_ASC = "isAsc";

    /**
     * 分页参数合理化
     */
    public static final String REASONABLE = "reasonable";

    /**
     * 封装分页对象
     */
    public static PageDomain getPageDomain() {
        PageDomain pageDomain = new PageDomain();
        HttpServletRequest request = ServletUtils.getRequest();
        StringBuffer data = new StringBuffer();

        String line = null;
        BufferedReader reader = null;
        try {
            reader = request.getReader();
            while (null != (line = reader.readLine()))
                data.append(line);
        } catch (IOException e) {

        } finally {
        }
        if (ObjectUtils.isEmpty(data)){
            pageDomain.setPageNum(Convert.toInt(ServletUtils.getParameter(PAGE_NUM), 1));
            pageDomain.setPageSize(Convert.toInt(ServletUtils.getParameter(PAGE_SIZE), 10));
            pageDomain.setOrderByColumn(ServletUtils.getParameter(ORDER_BY_COLUMN));
            pageDomain.setIsAsc(ServletUtils.getParameter(IS_ASC));
            pageDomain.setReasonable(ServletUtils.getParameterToBool(REASONABLE));
        }else {
            JSONObject jsonObject = JSONObject.parseObject(data.toString(),null);
            if (jsonObject.getIntValue(PAGE_NUM) != 0){
                pageDomain.setPageNum(jsonObject.getIntValue(PAGE_NUM));
            }else {
                pageDomain.setPageNum(Convert.toInt(ServletUtils.getParameter(PAGE_NUM), 1));
            }
            if (jsonObject.getIntValue(PAGE_SIZE) != 0){
                pageDomain.setPageSize(jsonObject.getIntValue(PAGE_SIZE));
            }else {
                pageDomain.setPageSize(Convert.toInt(ServletUtils.getParameter(PAGE_SIZE), 10));
            }
            pageDomain.setOrderByColumn(jsonObject.getString(ORDER_BY_COLUMN));
            pageDomain.setIsAsc(jsonObject.getString(IS_ASC));
            pageDomain.setReasonable(jsonObject.getBoolean(REASONABLE));
        }
        return pageDomain;
    }

    public static PageDomain buildPageRequest() {
        return getPageDomain();
    }
}
